const express = require("express");
const c = require("../connection");
const router = express.Router();

//  客户信息新增接口

router.post('/add',(req,res,next)=>{
  var obj=req.body
  c.query('insert into cs_customer set ?',[obj],(err,r)=>{
      if(err){
          return next(err)
      }
      console.log(r);
      res.send({
          code:200,
          msg:'客户信息新增成功'
      })
  })
})

//  客户信息查询接口

router.get("/search", (req, res, next) => {
  console.log(req.query);
  // var { cname, car_num, car_vin, tel } = req.query;
  var cname = cname == "undefined" ? "" : req.query.cname;
  var car_num = car_num == "undefined" ? "" : req.query.car_num;
  var car_vin = car_vin == "undefined" ? "" : req.query.car_vin;
  var tel = tel == "undefined" ? "" : req.query.tel;
  c.query(
    `select * from cs_customer where  cname like ? and car_num like ? and car_vin like ? and tel like ?`,
    [`%${cname}%`, `%${car_num}%`, `%${car_vin}%`, `%${tel}%`],
    (err, result) => {
      if (err) next(err);
      console.log(result);
      if (result.length > 0) {
        res.send({ code: 200, msg: "查询成功", data: result });
      } else {
        res.send({ code: 400, msg: "查询失败" });
      }
    }
  );
});

//  客户信息修改接口

router.post('/update', (req, res, next) => {
  var obj = req.body
  c.query('update cs_customer set ? where cid=?', [obj, obj.cid], (err, r) => {
    if (err) {
      return next(err)
    }
    console.log(r);
    if (r.changedRows == 0) {
      res.send({ code: 401, msg: '修改失败' })
    } else {
      res.send({ code: 200, msg: '修改成功', data: r })
    }
  })
})

//  客户信息删除接口

router.post('/delete', (req, res, next) => {
  var obj = req.body
  console.log(obj);
  c.query(`delete from cs_customer where cid=?`, [obj.cid], (err, r) => {
    console.log(r);
    if (err) {
      return next(err)
    }
    if (r.affectedRows === 1) {
      res.send({
        code: 200,
        msg: '删除成功',
        data: r
      })
    } else {
      res.send({
        code: 401,
        msg: '删除失败',
        data: r
      })
    }
  })
})
module.exports = router;
